package com.demo.algorithm;

/**
 * Created by hunter
 *
 * @Description 选择排序(拿首位或者末尾开始的值与每一个值比对交换,最后把最大或最小值交换放置首位或末尾)
 */
public class SelectionSort {

    public static void sort(Integer[] numbers) {
        if (numbers == null || numbers.length == 0) {
            return;
        }

        int length = numbers.length;
        for (int i = 0; i < length - 1; i++) {
            int idx = i;
            for (int j = i + 1; j < length; j++) {
                if (numbers[idx] > numbers[j]) {
                    idx = j;
                }
            }

            // 先交换idx，再进行值交换
            if (idx != i) {
                int t = numbers[i];
                numbers[i] = numbers[idx];
                numbers[idx] = t;
            }
        }
    }

    public static void main(String[] args) {
        Integer[] numbers = {5, 3, 1, 8, 2, 8, 9};
        sort(numbers);
        print(numbers);
    }

    private static void print(Integer[] numbers) {
        for (Integer i : numbers) {
            System.out.println(i);
        }
    }
}